package com.fs.decorator;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fs.Utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.Strings;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 简化了响应体加密操作
 * 取消数据传输中的加密
 */
@Slf4j
@SuppressWarnings("all")
public class RewriteResponseDecoratorL extends ServerHttpResponseDecorator {
    public RewriteResponseDecoratorL(ServerHttpResponse delegate) {
        super(delegate);
    }

    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
        log.info("" + this.getStatusCode().value());
        if (this.getStatusCode().equals(HttpStatus.OK) && body instanceof Flux) {
            //更新跨域
            this.getHeaders().setAccessControlAllowOrigin("*");
            this.getHeaders().setAccessControlAllowCredentials(true);
            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
            return super.writeWith(fluxBody.buffer().map(dataBuffers ->
            {
                DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                //零拷贝拼接
                DataBuffer join = dataBufferFactory.join(dataBuffers);
                byte[] oldContent = new byte[join.readableByteCount()];
                join.read(oldContent);
                //释放缓存
                DataBufferUtils.release(join);

                return dataBufferFactory.wrap(oldContent);
            }));
        }
        return super.writeWith(body);
    }

}
